Inject a Script into Document Head or Body Tags


You can inject js script into the document head dynamically like this :

const basicScript = document.createElement('script');

basicScript.type = 'text/javascript';

basicScript.innerHTML = `
    console.log('This is a basic script injection.');
`;

document.head.appendChild(basicScript);  // append script into head tag

// OR

document.body.appendChild(basicScript);  // append script into body tag

I followed this approach to dynamically inject JavaScript scripts into the <head> and <body> tags via an AJAX call in a cached Laravel application.

This method allows you to dynamically inject and execute a basic script into the document head or body.

You Might Also Like

Apply Styles to Multiple Elements

Apply a style to multiple elements at once by adding a class. Here highlighting selected list items...

Efficiently Append Multiple Elements

Appending multiple elements to the DOM can be inefficient if done individually. Use a document frag...